/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NameAuthorTable.java
 *
 * Created on May 5, 2010, 10:05:36 AM
 */

package org.dafe.partyband.gui.imports;

import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import org.dafe.partyband.gui.Utilities;
import org.dafe.partyband.gui.Utilities.CustomColumnFactory;
import org.dafe.partyband.importer.api.IImportRecipe;
import org.dafe.partyband.importer.api.IImporterServices;
import org.dafe.partyband.importer.api.ISongImport;
import org.dafe.partyband.importer.api.ISongImport.IImportIssue;
import org.dafe.partyband.importer.api.Utils;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.color.ColorUtil;
import org.jdesktop.swingx.decorator.BorderHighlighter;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.ComponentAdapter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.jdesktop.swingx.util.OS;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 *
 * @author dafe
 */
public class NameAuthorTable extends javax.swing.JPanel {

    private static final ISongImport.IEvaluator evaluator = Lookup.getDefault().lookup(IImporterServices.class).getImportEvaluator();

    private static final Class[] columnTypes = new Class [] {
        java.lang.Boolean.class, java.lang.String.class, java.lang.String.class
    };
    public static final String[] columnNames = new String[] {
        "doImportColumn", "songNameColumn", "songAuthorColumn"
    };

    private final IImportRecipe recipe;
    private final IssuesList issuesList;
    private final SongResourcesTable resourcesTable;

    /** Creates new form NameAuthorTable */
    public NameAuthorTable(final IImportRecipe recipe, IssuesList issuesList, SongResourcesTable resourcesTable) {
        this.recipe = recipe;
        this.issuesList = issuesList;
        this.resourcesTable = resourcesTable;

        initComponents();

        songsTable.addHighlighter(HighlighterFactory.createSimpleStriping());
        songsTable.addHighlighter(new BorderHighlighter(HighlightPredicate.HAS_FOCUS,
                BorderFactory.createLineBorder(Color.black)));
        songsTable.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                ColorUtil.setAlpha(songsTable.getSelectionBackground(), 30), null));

        // define column features and properties
        CustomColumnFactory customCF = new Utilities.CustomColumnFactory();
        CustomColumnFactory.ColumnDescription importCheckboxDesc = new CustomColumnFactory.ColumnDescription();
        importCheckboxDesc.title = "";
        importCheckboxDesc.tooltip = NbBundle.getMessage(NameAuthorTable.class, "HINT_ImportSongColumn");
        importCheckboxDesc.prototypeDescription = new CustomColumnFactory.PrototypeDescription("  ", 1.5f, 2.5f);
        importCheckboxDesc.cellEditor = new JXTable.BooleanEditor();
        customCF.setColumnDescription(columnNames[0], importCheckboxDesc);

        CustomColumnFactory.ColumnDescription songNameDesc = new CustomColumnFactory.ColumnDescription();
        songNameDesc.title = NbBundle.getMessage(NameAuthorTable.class, "TIT_SongColumn");
        songNameDesc.tooltip = NbBundle.getMessage(NameAuthorTable.class, "HINT_SongColumn");
        songNameDesc.cellEditor = new JXTable.GenericEditor();
        customCF.setColumnDescription(columnNames[1], songNameDesc);

        CustomColumnFactory.ColumnDescription authorDesc = new CustomColumnFactory.ColumnDescription();
        authorDesc.title = NbBundle.getMessage(NameAuthorTable.class, "TIT_AuthorColumn");
        authorDesc.tooltip = NbBundle.getMessage(NameAuthorTable.class, "HINT_AuthorColumn");
        authorDesc.cellEditor = new JXTable.GenericEditor();

        ColorHighlighter defectH = new ColorHighlighter(new HighlightPredicate() {
            public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
                int modelRow = adapter.convertRowIndexToModel(adapter.row);
                return hasSomeDefect(recipe.getSongImports().get(modelRow));
            }
        }, ColorUtil.setAlpha(Color.red, 20), null);

        ColorHighlighter warningH = new ColorHighlighter(new HighlightPredicate() {
            public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
                int modelRow = adapter.convertRowIndexToModel(adapter.row);
                ISongImport si = recipe.getSongImports().get(modelRow);
                if (hasSomeDefect(si)) {
                    return false;
                }
                return hasSomeWarning(si);
            }
        }, ColorUtil.setAlpha(Color.yellow, 20), null);
        
        customCF.setColumnDescription(columnNames[2], authorDesc);

        songsTable.setColumnFactory(customCF);

        songsTable.addHighlighter(warningH);
        songsTable.addHighlighter(defectH);

        final RecipeTableModel model = new RecipeTableModel();
        songsTable.setModel(model);

        // workaround for https://swingx.dev.java.net/issues/show_bug.cgi?id=1297
        if (OS.isLinux()) {
            UIManager.put("Table.focusSelectedCellHighlightBorder",
                    BorderFactory.createEmptyBorder(0, 0, 0, 0));
            UIManager.put("Table.focusCellHighlightBorder",
                    BorderFactory.createEmptyBorder(0, 0, 0, 0));
        }
    }

    public IImportRecipe getRecipe () {
        return recipe;
    }

    public Map<ISongImport, Boolean> getEnabledMap () {
        TableModel model = songsTable.getModel();
        Map<ISongImport, Boolean> result = new HashMap<ISongImport, Boolean>(model.getRowCount());
        List<? extends ISongImport> songImports = recipe.getSongImports();

        for (int i = 0; i < model.getRowCount(); i++) {
            result.put(songImports.get(i), (Boolean) model.getValueAt(i, 0));
        }

        return result;
    }

    JTable getTable () {
        return songsTable;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        songsTable = new org.jdesktop.swingx.JXTable();

        setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 2));

        songsTable.setShowHorizontalLines(false);
        songsTable.setShowVerticalLines(false);
        jScrollPane1.setViewportView(songsTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable songsTable;
    // End of variables declaration//GEN-END:variables

    private class RecipeTableModel extends AbstractTableModel {

        private final List<? extends ISongImport> songImports = recipe.getSongImports();
        private List<Boolean> importEnabled = new ArrayList<Boolean>(songImports.size());

        public RecipeTableModel() {
            for (ISongImport si : songImports) {
                importEnabled.add(!hasSomeDefect(si));
            }
        }

        @Override
        public int getRowCount() {
            return recipe.getSongImports().size();
        }

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return importEnabled.get(rowIndex);
                case 1:
                    return songImports.get(rowIndex).getSongToImport().getName();
                case 2:
                    return songImports.get(rowIndex).getSongToImport().getAuthor().getName();
            }
            throw new IllegalArgumentException();
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            ISongImport.IEvaluation eval = songImports.get(rowIndex).getEvaluation();
            switch (columnIndex) {
                case 0:
                    return !Utils.hasDefects(eval);
                case 1:
                    return eval.isImportEnabled(ISongImport.IEvaluation.Field.NAME);
                case 2:
                    return eval.isImportEnabled(ISongImport.IEvaluation.Field.AUTHOR);
            }
            throw new IllegalArgumentException();
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 0:
                    importEnabled.set(rowIndex, (Boolean) aValue);
                    importChanged(rowIndex);
                    break;
                case 1:
                    songImports.get(rowIndex).getSongToImport().setName((String)aValue);
                    songNameChanged(rowIndex);
                    break;
                case 2:
                    songImports.get(rowIndex).getSongToImport().getAuthor().setName((String)aValue);
                    authorNameChanged(rowIndex);
                    break;
                default:
                    throw new IllegalArgumentException();
            }
        }

        @Override
        public Class getColumnClass(int columnIndex) {
            return columnTypes [columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        private void authorNameChanged(int rowIndex) {
            ISongImport si = songImports.get(rowIndex);
            ISongImport.IEvaluation eval = si.getEvaluation();
            si.setEvaluation(evaluator.reevaluateAuthor(si, eval));
            importEnabled.set(rowIndex, !hasSomeDefect(si));
            issuesList.setContent(si.getEvaluation().getIssues(), si.getSongToImport().getName());
            importChanged(rowIndex);
        }

        private void importChanged(int rowIndex) {
            resourcesTable.setSongImport(songImports.get(rowIndex), importEnabled.get(rowIndex));
        }

        private void songNameChanged(int rowIndex) {
            ISongImport si = songImports.get(rowIndex);
            ISongImport.IEvaluation eval = si.getEvaluation();
            si.setEvaluation(evaluator.reevaluateSongName(si, eval));
            importEnabled.set(rowIndex, !hasSomeDefect(si));
            issuesList.setContent(si.getEvaluation().getIssues(), si.getSongToImport().getName());
            importChanged(rowIndex);
        }

    }

    private static boolean hasSomeDefect (ISongImport si) {
        for (IImportIssue issue : si.getEvaluation().getIssues()) {
            if (IImportIssue.Severity.DEFECT.equals(issue.getSeverity())) {
                return true;
            }
        }
        return false;
    }

    private static boolean hasSomeWarning (ISongImport si) {
        for (IImportIssue issue : si.getEvaluation().getIssues()) {
            if (IImportIssue.Severity.WARNING.equals(issue.getSeverity())) {
                return true;
            }
        }
        return false;
    }

}
